package com.ruoyi.wms.service.impl;

import java.util.List;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.wms.mapper.WmsLocationMapper;
import com.ruoyi.wms.domain.WmsLocation;
import com.ruoyi.wms.domain.WmsItemLocation;
import com.ruoyi.wms.service.IWmsLocationService;
import com.ruoyi.wms.service.IWmsItemLocationService;
import com.ruoyi.common.exception.ServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 库位信息Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-01-01
 */
@Service
public class WmsLocationServiceImpl implements IWmsLocationService 
{
    private static final Logger log = LoggerFactory.getLogger(WmsLocationServiceImpl.class);
    
    @Autowired
    private WmsLocationMapper wmsLocationMapper;
    
    @Autowired
    private IWmsItemLocationService wmsItemLocationService;

    /**
     * 查询库位信息
     * 
     * @param id 库位信息主键
     * @return 库位信息
     */
    @Override
    public WmsLocation selectWmsLocationById(Long id)
    {
        return wmsLocationMapper.selectWmsLocationById(id);
    }

    /**
     * 查询库位信息列表
     * 
     * @param wmsLocation 库位信息
     * @return 库位信息
     */
    @Override
    public List<WmsLocation> selectWmsLocationList(WmsLocation wmsLocation)
    {
        // 设置租户ID
        wmsLocation.setTenantId(SecurityUtils.getTenantId());
        return wmsLocationMapper.selectWmsLocationList(wmsLocation);
    }

    /**
     * 新增库位信息
     * 
     * @param wmsLocation 库位信息
     * @return 结果
     */
    @Override
    public int insertWmsLocation(WmsLocation wmsLocation)
    {
        wmsLocation.setTenantId(SecurityUtils.getTenantId());
        wmsLocation.setCreateBy(SecurityUtils.getUsername());
        wmsLocation.setCreateTime(DateUtils.getNowDate());
        return wmsLocationMapper.insertWmsLocation(wmsLocation);
    }

    /**
     * 修改库位信息
     * 
     * @param wmsLocation 库位信息
     * @return 结果
     */
    @Override
    public int updateWmsLocation(WmsLocation wmsLocation)
    {
        wmsLocation.setUpdateBy(SecurityUtils.getUsername());
        wmsLocation.setUpdateTime(DateUtils.getNowDate());
        return wmsLocationMapper.updateWmsLocation(wmsLocation);
    }

    /**
     * 批量删除库位信息
     * 
     * @param ids 需要删除的库位信息主键
     * @return 结果
     */
    @Override
    public int deleteWmsLocationByIds(Long[] ids)
    {
        return wmsLocationMapper.deleteWmsLocationByIds(ids);
    }

    /**
     * 删除库位信息信息
     * 
     * @param id 库位信息主键
     * @return 结果
     */
    @Override
    public int deleteWmsLocationById(Long id)
    {
        return wmsLocationMapper.deleteWmsLocationById(id);
    }

    /**
     * 根据库位编码查询库位信息
     * 
     * @param locationCode 库位编码
     * @return 库位信息
     */
    @Override
    public WmsLocation selectWmsLocationByCode(String locationCode)
    {
        return wmsLocationMapper.selectWmsLocationByCode(locationCode, SecurityUtils.getTenantId());
    }

    /**
     * 根据库区ID查询库位列表
     * 
     * @param areaId 库区ID
     * @return 库位信息集合
     */
    @Override
    public List<WmsLocation> selectWmsLocationByAreaId(Long areaId)
    {
        return wmsLocationMapper.selectWmsLocationByAreaId(areaId, SecurityUtils.getTenantId());
    }

    /**
     * 根据仓库ID查询库位列表
     * 
     * @param warehouseId 仓库ID
     * @return 库位信息集合
     */
    @Override
    public List<WmsLocation> selectWmsLocationByWarehouseId(Long warehouseId)
    {
        return wmsLocationMapper.selectWmsLocationByWarehouseId(warehouseId, SecurityUtils.getTenantId());
    }

    /**
     * 校验库位编码是否唯一
     * 
     * @param wmsLocation 库位信息
     * @return 结果
     */
    @Override
    public boolean checkLocationCodeUnique(WmsLocation wmsLocation)
    {
        Long locationId = StringUtils.isNull(wmsLocation.getId()) ? -1L : wmsLocation.getId();
        WmsLocation info = wmsLocationMapper.selectWmsLocationByCode(wmsLocation.getLocationCode(), SecurityUtils.getTenantId());
        if (StringUtils.isNotNull(info) && info.getId().longValue() != locationId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 根据仓库ID和库位类型查询库位列表
     * 
     * @param warehouseId 仓库ID
     * @param locationType 库位类型
     * @return 库位信息集合
     */
    @Override
    public List<WmsLocation> selectWmsLocationByWarehouseIdAndType(Long warehouseId, Integer locationType)
    {
        return wmsLocationMapper.selectWmsLocationByWarehouseIdAndType(warehouseId, locationType, SecurityUtils.getTenantId());
    }

    /**
     * 获取推荐库位
     * 
     * @param itemId 商品ID
     * @param warehouseId 仓库ID
     * @return 推荐库位信息
     */
    @Override
    public WmsLocation getRecommendedLocation(Long itemId, Long warehouseId)
    {
        log.info("开始获取推荐库位，商品ID: {}, 仓库ID: {}, 租户ID: {}", itemId, warehouseId, SecurityUtils.getTenantId());
        
        // 1. 先查询商品库位关系表，获取status为0的记录，按priority排序取第一条
        List<WmsItemLocation> itemLocations = wmsItemLocationService.selectRecommendedLocationsByItemId(itemId, warehouseId);
        log.info("查询商品库位关系结果，数量: {}", itemLocations != null ? itemLocations.size() : 0);
        
        if (itemLocations != null && !itemLocations.isEmpty()) {
            // 找到第一个状态为0的记录
            for (WmsItemLocation itemLocation : itemLocations) {
                log.info("检查商品库位关系，ID: {}, 状态: {}, 库位ID: {}", itemLocation.getId(), itemLocation.getStatus(), itemLocation.getLocationId());
                if (itemLocation.getStatus() != null && itemLocation.getStatus() == 0) {
                    WmsLocation location = selectWmsLocationById(itemLocation.getLocationId());
                    if (location != null && location.getWarehouseId().equals(warehouseId)) {
                        log.info("找到推荐库位（商品库位关系），库位ID: {}, 库位编码: {}", location.getId(), location.getLocationCode());
                        return location;
                    }
                }
            }
        }
        
        // 2. 如果没有找到，则查找当前仓库下location_type为1（临时库位）的库位，按priority排序取第一条
        log.info("未找到商品库位关系，开始查找临时库位，仓库ID: {}, 库位类型: 1, 租户ID: {}", warehouseId, SecurityUtils.getTenantId());
        List<WmsLocation> tempLocations = selectWmsLocationByWarehouseIdAndType(warehouseId, 1);
        log.info("查询临时库位结果，数量: {}", tempLocations != null ? tempLocations.size() : 0);
        
        if (tempLocations != null && !tempLocations.isEmpty()) {
            WmsLocation tempLocation = tempLocations.get(0);
            log.info("找到临时库位，库位ID: {}, 库位编码: {}, 库位类型: {}, 状态: {}", 
                tempLocation.getId(), tempLocation.getLocationCode(), tempLocation.getLocationType(), tempLocation.getStatus());
            return tempLocation;
        }
        
        // 3. 如果都没有找到，抛出异常
        log.error("未找到任何可用库位，商品ID: {}, 仓库ID: {}, 租户ID: {}", itemId, warehouseId, SecurityUtils.getTenantId());
        throw new ServiceException("请维护一个临时库位");
    }
}